

package com.woniuxy.listener;

import com.rabbitmq.client.Channel;
import com.woniuxy.entity.Mail;
import com.woniuxy.entity.TopicMail;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author: 马宇航
 * @Description: TODO
 * @DateTime: 22/10/19/0019 16:50
 * @Component: 成都蜗牛学苑
 **/
@Component
public class TopicListener2 {
    static int i = 0;
    @RabbitListener(queues = {"topicQueue2"})
    public void messageReceive(Mail mail, Channel channel, Message message) throws IOException, InterruptedException {
        //设置限流
        channel.basicQos(0,2,false);
        //如果是偶数就确认消息
        if (i++%2==0){

            //获取消息的tagid
            long deliveryTag = message.getMessageProperties().getDeliveryTag();
            Thread.sleep(2000);
            //业务处理没异常则 确认该条消息
            channel.basicAck(deliveryTag,false);
            System.out.println("第二个topic消费者收到消息："+mail);
            System.out.println("对应的routingkey是："+((TopicMail)mail).getRoutingkey());
        }else {
            //重回队列
            System.out.println("拒绝消息并重回队列");
            //拒绝ack确认，并requeue重入队列
//            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            //不重新入队列，直接丢弃
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
            //不拒绝消息，但是要转发消息
            channel.basicPublish("deadExchange","deadMessage",null,message.getBody());
        }
    }
}